// 重写 数组中的部分方法

let oldArrayProto = Array.prototype;

// newArrayProto.__proto__ == oldArrayProto
export let newArrayProto = Object.create(oldArrayProto);

let methods = [
  //找到所有修改原数组的方法
  "push",
  "pop",
  "shift",
  "unshift",
  "reverse",
  "sort",
  "splice",
];

methods.forEach((method) => {
  newArrayProto[method] = function (...args) {
    // 调用重写的方法相当于调用原生的方法
    const result = oldArrayProto[method].call(this, ...args); //函数劫持
    let inserted;
    let ob = this.__ob__
    switch (method) {
      case "push":
      case "unshift":
        inserted = args;
        break;
      case "splice":
        inserted = args.slice(2);
      default:
        break;
    }
    // 有数组有新增的内容，对新增的内容添加响应式
    if (inserted) {
      ob.observeArray(inserted)
    }

    ob.dep.notify() //数组发生变化 通知对应的watcher实例更新
    return result;
  };
});
